<?php
/**
 * 验证余额
 * Created by PhpStorm.
 * Author: 张志祥
 * QQ: 786811688
 * Phone: 13306281319
 * Date: 2017/5/21
 * Time: 16:39
 */

// 机构表余额汇总 = 机构表期初余额汇总 + 机构流水表入金汇总 + 机构流水表出金汇总 + 机构流水表手续费汇总 + 机构流水表盈亏汇总 + 机构流水表异常订单汇总
// 客户表余额汇总 = 客户表期初余额汇总 + 客户流水表金额汇总 + 客户流水表手续费汇总
// 客户表余额汇总 = 客户表期初余额汇总 + 历史订单表盈亏汇总 - 客户流水表手续费汇总

include 'pub.php'; // 公共函数

// 读取期初值
$init_balance = json_decode(file_get_contents(dirname(__FILE__) . '/balance_init.log'));
$balance_jq = $init_balance->balance_jq;
$balance_kh = $init_balance->balance_kh;
echo "机构表期初余额汇总：$balance_jq\n";
echo "客户表期初余额汇总：$balance_kh\n";

// 机构表余额汇总
$sql = 'SELECT Sum(zzx_jg_company.balance) as balance FROM zzx_jg_company';
$res = $my_conn->query($sql);
$balance_jq_new = mysqli_fetch_array($res, MYSQLI_ASSOC)['balance'];

// 客户表余额汇总
$sql = 'SELECT Sum(zzx_wp_userinfo.balance) as balance FROM zzx_wp_userinfo';
$res = $my_conn->query($sql);
$balance_kh_new = mysqli_fetch_array($res, MYSQLI_ASSOC)['balance'];

// 机构流水表汇总
$sql = 'SELECT Sum(zzx_balanceinfo_jg.atm) as atm FROM zzx_balanceinfo_jg ';
$res = $my_conn->query($sql);
$sum_jgls = mysqli_fetch_array($res, MYSQLI_ASSOC)['atm'];
echo "机构流水表汇总：$sum_jgls\n";

// 历史订单表的盈亏汇总
$sql = 'SELECT Sum(zzx_order_history.ploss) as pl FROM zzx_order_history';
$res = $my_conn->query($sql);
$pl_history = mysqli_fetch_array($res, MYSQLI_ASSOC)['pl'];
echo "历史订单表的盈亏汇总：$pl_history\n";

// 异常订单表的汇总
$sql = 'SELECT Sum(zzx_order_error.money) as m, SUM(zzx_order_error.service_fee) as sf FROM zzx_order_error';
$res = $my_conn->query($sql);
$error_orders = mysqli_fetch_array($res, MYSQLI_ASSOC);
$error_money = $error_orders['m'];
$error_fee = $error_orders['sf'];
echo "异常订单表的金额汇总：$error_money\n";
echo "异常订单表的手续费汇总：$error_fee\n";

// 客户流水表汇总
$sql = 'SELECT Sum(kh.atm) as atm, Sum(kh.proce) as fee FROM zzx_balanceinfo_kh as kh';
$res = $my_conn->query($sql);
$data = mysqli_fetch_array($res, MYSQLI_ASSOC);
$sum_khls = $data['atm']; // 发生金额
$sum_fee = $data['fee']; // 手续费
echo "客户流水表汇总：$sum_khls\n";
echo "客户流水表手续费汇总：$sum_fee\n";


// 验证 ##################################################################################
echo "\n验证：\n";

// 机构表余额汇总 = 机构表期初余额汇总 + 机构流水表汇总
if (bccomp($balance_jq_new, $balance_jq + $sum_jgls, 4) == 0) {
    echo "机构表余额汇总 = 机构表期初余额汇总 + 机构流水表金额汇总：ok\n";
} else {
    echo "机构表余额汇总$balance_jq_new = 机构表期初余额汇总$balance_jq + 机构流水表金额汇总{$sum_jgls} ：error\n";
}

// 客户表余额汇总 = 客户表期初余额汇总 + 客户流水表金额汇总 + 客户流水表手续费汇总
if (bccomp($balance_kh_new, $balance_kh + $sum_khls + $sum_fee, 4) == 0) {
    echo "客户表余额汇总 = 客户表期初余额汇总 + 客户流水表金额汇总（入、出金，下单，平仓，异常，手续费）：ok\n";
} else {
    echo "客户表余额汇总$balance_kh_new = 客户表期初余额汇总$balance_kh + 客户流水表金额汇总$sum_khls + 客户流水表手续费汇总$sum_fee ：error\n";
}

echo "\n\n";
